package com.wawi.utils.gen;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

public class DBUtils {
	private static String driver;
	private static String url;
	private static String username;
	private static String password;
	
	static {
		try {
			username = ResourceBundle.getBundle("jdbc").getString("username");
			password = ResourceBundle.getBundle("jdbc").getString("password");
			url = ResourceBundle.getBundle("jdbc").getString("url");
			driver = ResourceBundle.getBundle("jdbc").getString("driver");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 获取数据库连接
	 */
	public static Connection getConnection() {
		Connection con=null;
		try {
			Class.forName(driver);
			con = DriverManager.getConnection(url, username, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return con;
	}

	/**
	 * 关闭数据库连接
	 */
	public static void close(ResultSet rs, PreparedStatement ps, Connection con) {
		try {
			if (rs != null)
				rs.close();
			if (ps != null)
				ps.close();
			if (con != null)
				con.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 获取所有数据库表名
	 */
	public static String[] getTableNames(Connection conn){
		String[] tableNames=new String[]{};
		try {
			 DatabaseMetaData meta = conn.getMetaData();  
			 ResultSet rs = meta.getTables(null, null, null, new String[] { "TABLE" });  
			 rs.last(); 
			 tableNames=new String[rs.getRow()];
			 int i=0;
			 rs.beforeFirst();
			 while (rs.next()) {  
				 tableNames[i]=rs.getString(3);
			     i++;
			 } 
		} catch (Exception e) {
			e.printStackTrace();
		}
		return tableNames;
	}
	public Map<String, Object> getEntity(String sql,Connection conn) {
		Map<String, Object> entity = new HashMap<String, Object>();
		PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			ResultSetMetaData rsmd = rs.getMetaData();
			int column = rsmd.getColumnCount();
			while (rs.next()) {
				Object[] objects = new Object[column];
				Map<String, Object> map = new HashMap<String, Object>();
				for (int i = 0; i < objects.length; i++) {
					Object value = rs.getObject(i + 1);
					String key = rsmd.getColumnName(i + 1);
					map.put(key, value);
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} 
		return entity;
	}
}